//
//  SetUpViewController.m
//  HappilyLoan
//
//  Created by 纵情向前 on 2017/4/10.
//  Copyright © 2017年 zongqingxiangqian. All rights reserved.
//

#import "SetUpViewController.h"
#import "AlertBoxView.h"
#import "PublicClass.h"
#import "SetUpTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "AnimatingView.h"
#import "ZFHeader.h"
#import "JPUSHService.h"

@interface SetUpViewController ()<UITableViewDelegate,UITableViewDataSource>
{
        NSInteger  _index;//记录当前点击的cell
}

@property(nonatomic,strong)AlertBoxView *alertBox;
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *dataSource1;
@property (nonatomic, strong)UIButton *QuitButton;
@end

@implementation SetUpViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationItem.title = @"设置中心";
    
    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60) forBarMetrics:UIBarMetricsDefault];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_sm_whiteback"] style:UIBarButtonItemStylePlain target:self action:@selector(toBack)];
    self.view.backgroundColor = GetColor(246, 247, 248, 1);
    
    self.dataSource1 = [NSMutableArray arrayWithObjects:@"清除缓存",@"检查更新",nil];
  
    _index = -1;
    [self setUpQuit];
    [self.view addSubview:self.QuitButton];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.alertBox];
    // Do any additional setup after loading the view from its nib.
}
- (void)setUpQuit{
    _QuitButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _QuitButton.bounds = CGRectMake(0, 0, ADAPTATION_WIDTH((375-30)), 40);
    _QuitButton.center = CGPointMake(MAINSCREEN_WIDTH/2, 64+ADAPTATION_HEIGHT(225));
    _QuitButton.backgroundColor = GetColor(246, 25, 66, 1);
    [_QuitButton setTitle:@"退出登录" forState:UIControlStateNormal];
    _QuitButton.layer.cornerRadius = 10;
    _QuitButton.layer.masksToBounds = YES;
     [_QuitButton setShadowWidth:2 shadowHeight:2 shadowColor:Main_Color1 radius:10];
    [_QuitButton addTarget:self action:@selector(quitAction:) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark - tableViewDelegate
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64+15/H, SCREEN_WIDTH, ADAPTATION_HEIGHT(120)) style:UITableViewStylePlain];

//        _tableView.backgroundColor = [UIColor colorWithWhite:1 alpha:0.5];
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.layer.cornerRadius = 5;
        _tableView.layer.masksToBounds = YES;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.scrollEnabled = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
        [_tableView registerClass:[SetUpTableViewCell class] forCellReuseIdentifier:@"AboutMineCell"];
    }
    return _tableView;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"phone"] isEqualToString:@"18725835901"]) {
        
        return 1;
    }
    return 2;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return ADAPTATION_HEIGHT(60);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SetUpTableViewCell *setUpCell = [tableView dequeueReusableCellWithIdentifier:@"AboutMineCell" forIndexPath:indexPath];

    setUpCell.titleLabel.text = self.dataSource1[indexPath.row];
    
    if (indexPath.row == 0) {
        float tmpSize = [[SDImageCache sharedImageCache] getSize];
        float newTmpsize = tmpSize/1024/1024;
        setUpCell.detialLabel.text = [NSString stringWithFormat:@"%.2fM",newTmpsize];
    }
    if (indexPath.row == 1) {
        //获取本地软件的版本号
        NSString *localVersion = [[[NSBundle mainBundle]infoDictionary] objectForKey:@"CFBundleShortVersionString"];
        setUpCell.detialLabel.text = localVersion;
        
    }
    
    UILabel *label = [[UILabel alloc] init];
    label.frame = CGRectMake(ADAPTATION_WIDTH(10), ADAPTATION_HEIGHT(59), ADAPTATION_WIDTH((375-20)), ADAPTATION_HEIGHT(1));
    label.backgroundColor = GetColor(215, 215, 215, 1);
    [setUpCell addSubview:label];
    setUpCell.selectionStyle = UITableViewCellSeparatorStyleNone;
    setUpCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;//右箭头
    return setUpCell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (_index == indexPath.row) {
        return;
    }
    if (indexPath.row == 0){
        float tmpSize = [[SDImageCache sharedImageCache] getSize];
        float newTmpsize = tmpSize/1024/1024;
        if (newTmpsize != 0) {
            UIAlertController *alert=[UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"当前缓存大小为:%.2fM,确定清除吗？",newTmpsize] preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * sureAct1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            [[SDImageCache sharedImageCache] clearDisk];
            [self.tableView reloadData];
            
        }];
        UIAlertAction * sureAct2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alert addAction:sureAct1];
        [alert addAction:sureAct2];
        [self presentViewController:alert animated:NO completion:nil];
        }else{
            [self.alertBox appearAndDisappearAlertWithString:@"当前无缓存内容"];
        }
        
    }
    if (indexPath.row == 1){
        NSString *newVersion;
        NSURL *url = [NSURL URLWithString:@"https://itunes.apple.com/cn/app/id1230934309?mt=8"];//这个URL地址是该app在iTunes connect里面的相关配置信息。其中id是该app在app store唯一的ID编号。
        NSString *jsonResponseString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
        NSLog(@"通过appStore获取的数据信息：%@",jsonResponseString);
        
        NSData *data = [jsonResponseString dataUsingEncoding:NSUTF8StringEncoding];
        
        //    解析json数据
        
        id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSArray *array = json[@"results"];
        
        for (NSDictionary *dic in array) {
            
            
            newVersion = [dic valueForKey:@"version"];
            
        }
        
    //NSLog(@"通过appStore获取的版本号是：%@",newVersion);
        
        //获取本地软件的版本号
        NSString *localVersion = [[[NSBundle mainBundle]infoDictionary] objectForKey:@"CFBundleVersion"];
        
        NSString *msg = [NSString stringWithFormat:@"你当前的版本是V%@，发现新版本V%@，是否下载新版本？",localVersion,newVersion];
        
        //对比发现的新版本和本地的版本
        if ([newVersion floatValue] > [localVersion floatValue])
        {
            
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"升级提示"message:msg preferredStyle:UIAlertControllerStyleAlert];
            
            [self presentViewController:alert animated:YES completion:nil];
            
            
            [alert addAction:[UIAlertAction actionWithTitle:@"现在升级" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/cn/app/id1230934309?mt=8"]];//这里写的URL地址是该app在app store里面的下载链接地址，其中ID是该app在app store对应的唯一的ID编号。
                NSLog(@"点击现在升级按钮");
            }]];
            
            [alert addAction:[UIAlertAction actionWithTitle:@"下次再说" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"点击下次再说按钮");  
            }]];  
        }
    }
}
- (void)quitAction:(UIButton *)sender{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提醒" message:@"是否退出登录" preferredStyle:1];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:2 handler:^(UIAlertAction * _Nonnull action) {
        [self chooseType:1];
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self chooseType:2];
    }];
    [alert addAction:action1];
    [alert addAction:action2];
    [self presentViewController:alert animated:NO completion:nil];
    
}
- (void)chooseType:(NSInteger)type {
    
    if (type == 1) {
        
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults removeObjectForKey:@"userid"];
        [userDefaults removeObjectForKey:@"info_progress"];
        [userDefaults removeObjectForKey:@"phone"];
        [userDefaults removeObjectForKey:@"user_name"];
        [JPUSHService setAlias:@"" callbackSelector:nil object:nil];
        [userDefaults synchronize];
    }
//    [self.navigationController popViewControllerAnimated:YES];
    UITabBarController *tabbarVC = (UITabBarController *)[UIApplication sharedApplication].delegate.window.rootViewController;
    tabbarVC.selectedIndex = 0;
    AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    appdelegate.exitLogin = @"退出登录";
}

-(void)toBack{
    [self.navigationController popViewControllerAnimated:YES];
}

- (AlertBoxView *)alertBox
{
    if (!_alertBox) {
        _alertBox = [[AlertBoxView alloc] init];
    }
    return _alertBox;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
     _index = -1;//初始化
    [MobClick beginLogPageView:@"setUpView"];
    self.navigationController.navigationBarHidden = NO;
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"setUpView"];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
